package com.nulldev.util.web.HttpClient.contentGen;

public class MultipartFormDataGenerator implements GeneratableContent {

	private final String boundary;
	private final StringBuilder builder = new StringBuilder();
	private static final String LINE_FEED = "\r\n";
	private static final String charset = "UTF-8";

	public MultipartFormDataGenerator() {
		this.boundary = "===" + System.currentTimeMillis() + "===";
	}

	public MultipartFormDataGenerator add(final String key, final String value) {
		if (key == null || key.isEmpty())
			return this;
		if (value == null)
			return this;
		this.builder.append("--" + boundary).append(LINE_FEED);
		this.builder.append("Content-Disposition: form-data; name=\"" + key + "\"").append(LINE_FEED);
		this.builder.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
		this.builder.append(LINE_FEED);
		this.builder.append(value).append(LINE_FEED);
		return this;
	}

	@Override
	public long getContentLength() {
		return this.builder.length();
	}

	@Override
	public String make() {
		return this.builder.toString();
	}

	@Override
	public void reset() {
		this.builder.setLength(0);
	}

	@Override
	public String getContentType() {
		return "multipart/form-data; boundary=" + this.boundary;
	}

}
